import axios from "axios";
import toastr, { error } from "toastr";
// service
import { handleLogout } from '@src/service/login.js';

const advServer = axios.create({
  baseURL: SERVER_URL,
  timeout: 5000
});

// 添加请求拦截器
advServer.interceptors.request.use(config => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.set('token', token)
  }
  return config;
});

// 添加响应拦截器
advServer.interceptors.response.use(function (response) {
  if (response.data.ok === 1) {
    return response.data;
  }

  if (response.data.ok === -2) {
    handleLogout()
  }

  toastr.error("请求服务器发生异常：" + response.data.msg);
  return new Promise(() => { })

}, function (error) {
  const msg = error?.response?.data?.msg
  toastr.error(`请求服务器发生异常${msg ? '：' + msg : ''}`);
  return new Promise(() => { })
});


export default advServer;